package com.by.executor;

/**
 * @version 1.0
 * @Author 彭彦彬
 * @Date 2025/4/8 21:15
 * @注释
 */



import com.by.config.Configuration;
import com.by.mapping.MappedStatement;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor {
    private Configuration configuration;

    public SimpleExecutor(Configuration configuration) {
        this.configuration = configuration;
    }

    public <T> List<T> query(MappedStatement mappedStatement, Object parameter) throws Exception {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 获取数据库连接
            Class.forName(configuration.getDriver());
            connection = DriverManager.getConnection(configuration.getUrl(), configuration.getUsername(), configuration.getPassword());

            // 预编译 SQL
            String sql = mappedStatement.getSql();
            preparedStatement = connection.prepareStatement(sql);

            if (parameter != null) {
                preparedStatement.setObject(1, parameter);
            }

            // 执行查询
            resultSet = preparedStatement.executeQuery();

            // 封装结果
            List<T> results = new ArrayList<>();
            while (resultSet.next()) {
                Class<?> resultType = mappedStatement.getResultType();
                T result = (T) resultType.getDeclaredConstructor().newInstance();

                // 使用显式的 Field 类型
                for (java.lang.reflect.Field field : resultType.getDeclaredFields()) {
                    field.setAccessible(true);
                    field.set(result, resultSet.getObject(field.getName()));
                }

                results.add(result);
            }
            return results;
        } finally {
            if (resultSet != null) resultSet.close();
            if (preparedStatement != null) preparedStatement.close();
            if (connection != null) connection.close();
        }
    }
}
